import 'dart:async';

import 'package:demo/view/lock/read_write_lock.dart';
import 'package:flutter/material.dart';

class LockPage extends StatefulWidget {
  const LockPage({super.key});

  @override
  _LockPageState createState() => _LockPageState();
}

class _LockPageState extends State<LockPage> {
  final _readWriteLock = ReadWriteLock();
  List<int> _data = [];
  late Timer _refreshTimer;

  @override
  void initState() {
    super.initState();
    _refreshTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      _doRead();
    });
  }

  @override
  void dispose() {
    _refreshTimer.cancel();
    _readWriteLock.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('读写锁演示'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                  onPressed: _doTwoWrite,
                  child: const Text('写入数据'),
                ),
                ElevatedButton(
                  onPressed: _clearData,
                  child: const Text('清除数据'),
                ),
              ],
            ),
            const SizedBox(height: 16),
            Expanded(
              child: ListView.builder(
                itemCount: _data.length,
                itemBuilder: (context, index) {
                  return Card(
                    child: ListTile(
                      title: Text('数据 ${_data[index]}'),
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _doTwoWrite() async {
    for(int i = 0; i < 10; i++) {
      await _doWrite();
    }

  }

  Future<void> _doWrite() async {
    await _readWriteLock.write(() async {
      setState(() {
        for(int i = 0; i < 100; i++) {
          _data.add(i);
        }
      });
    });
  }

  Future<void> _doRead() async {
    await _readWriteLock.read(() async {
      print(_data);
    });
  }

  Future<void> _clearData() async {
    await _readWriteLock.write(() async {
      setState(() {
        _data.clear();
      });
    });
  }
}
